angular.module('start.user.useredit.ctrl', [])

  /*
  app 需要引入服务
  $$cordovaImagePicker 图片选择
  $$cordovaCamera
   */
  .controller('UserEditCtrl', function($scope, $rootScope, $ionicActionSheet, $$WeixinConfigService, $$cordovaCamera, $timeout, $location, $ionicModal, $ionicLoading, $$UserEditService, $$UploadImageService, $$UserDataService, $ionicPopup, $$LocalStorage, $$cordovaImagePicker, $$UploadImageService) {
    console.log("UserEditCtrl");

    // userEdit 页面必须登录
    // if ($rootScope.needLogin() == false) {
    //     return;
    // }

    $scope.modal_avatar = {};
    $scope.modal_signature = {};
    $scope.modal_pwd = {};

    $scope.userMsg = {
      signature: $rootScope.userData.signature,
      password: "",
      avatar: ""
    };


    // 初始化 用户编辑 头像弹出窗口
    $ionicModal.fromTemplateUrl('userEditModel_avatar.html', {
      scope: $scope,
      animation: 'slide-in-right'
    }).then(function(modal) {
      $scope.modal_avatar = modal;
    });
    // 初始化 用户编辑 密码弹出窗口
    $ionicModal.fromTemplateUrl('userEditModel_pwd.html', {
      scope: $scope,
      animation: 'slide-in-right'
    }).then(function(modal) {
      $scope.modal_pwd = modal;
    });
    // 初始化 用户编辑 个性签名弹出窗口
    $ionicModal.fromTemplateUrl('userEditModel_signature.html', {
      scope: $scope,
      animation: 'slide-in-right'
    }).then(function(modal) {
      $scope.modal_signature = modal;
    });

    //监听离开页面时关闭model
    $scope.$on("$ionicView.beforeLeave", function() {
      console.info("UserEditCtrl--$ionicView.beforeLeave ");
      $scope.modal_avatar.remove();
      $scope.modal_signature.remove();
      $scope.modal_pwd.remove();
    });

    // model 中的图片节点
    var userEditDataAvatar = document.getElementById("userEditDataAvatar");
    // 打开 修改头像 model
    $scope.openModel_avatar = function() {
      $scope.modal_avatar.show();
      // 为 model 中的图片赋值
      userEditDataAvatar = document.getElementById("userEditDataAvatar");
      userEditDataAvatar.src = $rootScope.userData.headPic;
      // 为input增加改变事件
      var userEditAvatarInput = document.getElementById("userEditAvatarInput");
      userEditAvatarInput.addEventListener('change', readFileUserEditAvatarInput, false);
      // 为图片增加点击事件 触发input的点击事件
      // 先移除元素的点击绑定事件 保证只能触发一次点击事件
      $("#userEditDataAvatar").unbind('click');
      $("#userEditDataAvatar").on('click', function() {
        if ($rootScope.config.isWebView) { // app端中
          // 选择上传方式
          var hideSheet = $ionicActionSheet.show({
            buttons: [
              { text: '相机拍照' },
              { text: '手机相册' }
            ],
            // destructiveText: 'Delete',
            titleText: '选择图片上传方式',
            cancelText: '取消',
            cancel: function() {
              // add cancel code..
            },
            buttonClicked: function(index) {
              if (index == 0) {
                // 调用摄像头拍照
                var options = {
                  quality: 50,
                  destinationType: Camera.DestinationType.DATA_URL,
                  sourceType: Camera.PictureSourceType.CAMERA,
                  allowEdit: true,
                  encodingType: Camera.EncodingType.JPEG,
                  targetWidth: 100,
                  targetHeight: 100,
                  popoverOptions: CameraPopoverOptions,
                  saveToPhotoAlbum: false,
                  correctOrientation: true
                };
                $$cordovaCamera.getPicture(options).then(function(imageData) {
                  var base64 = "data:image/jpeg;base64," + imageData;
                  userEditDataAvatar = document.getElementById("userEditDataAvatar");
                  hideSheet();
                  userEditDataAvatar.src = base64;
                }, function(err) {
                  // error
                });
              } else if (index == 1) {
                // 调用手机相册
                var options = {
                  maximumImagesCount: 1,
                  width: 100,
                  height: 100,
                  quality: 50
                };
                $$cordovaImagePicker.getPictures(options)
                  .then(function(results) {
                    // console.log(results);
                    var image = new Image();
                    image.src = results[0];
                    image.onload = function() {
                      var canvas = document.createElement("canvas");
                      canvas.width = this.width;
                      canvas.height = this.height;
                      var ctx = canvas.getContext("2d");
                      ctx.drawImage(this, 0, 0, this.width, this.height);
                      var ext = this.src.substring(this.src.lastIndexOf(".") + 1).toLowerCase();
                      var base64 = canvas.toDataURL("image/" + ext);
                      userEditDataAvatar = document.getElementById("userEditDataAvatar");
                      hideSheet();
                      userEditDataAvatar.src = base64;
                      // console.log(base64);
                    };
                  }, function(error) {});
              }
            }
          });
        } else { // 浏览器中
          $("#userEditAvatarInput").trigger('click');
        }
      });
    };

    // input 文件改变触发事件
    function readFileUserEditAvatarInput() {
      var file = this.files[0];
      console.log(file);
      // // console.log(file.type)
      //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
      if (!/image\/\w+/.test(file.type)) {
        alert('请确保文件为图像类型');
        return false;
      } else {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          userEditDataAvatar = document.getElementById("userEditDataAvatar");
          userEditDataAvatar.src = this.result;
          // console.log(this.result);
        };
      }
    }

    //上传头像 并保存用户信息
    $scope.edituseruploadImage = function() {
      //未选择图片
      if ($rootScope.userData.headPic == userEditDataAvatar.src) {
        $ionicLoading.show({
          template: "请选择图片",
          noBackdrop: true,
          duration: 1500
        });
        return;
      }
      $ionicLoading.show({
        template: "数据提交中",
        noBackdrop: true,
      });
      userEditDataAvatar = document.getElementById("userEditDataAvatar");
      // 上传接口
      // $$UploadImageService.uploadImageOne(userEditDataAvatar.src, "userAvatar").success(function(data) {
      //     console.log(data);
      //     if (data.code == 200) { // 上传成功返回新url
      //         $scope.userMsg.avatar = data.result.url;
      //         $scope.updateUserMsg();
      //     } else {
      //         $ionicLoading.show({
      //             template: data.message,
      //             noBackdrop: true,
      //             duration: 1500
      //         });
      //     }
      // });
      $$UploadImageService.uploadImage(userEditDataAvatar.src)
        .then(function(res) {
          $scope.userMsg.avatar = res.data.pic;
          $scope.updateUserMsg();
        });


    };

    //修改密码 并保存用户信息
    $scope.editUserPassword = function() {
      $ionicLoading.show({
        template: "数据提交中",
        noBackdrop: true,
      });
      // 校验密码
      if ($scope.userMsg.password.length < 6 || $scope.userMsg.password.length > 12 || $scope.userMsg.password == null) {
        $ionicLoading.show({
          template: "请输入正确6~12位的密码",
          noBackdrop: true,
          duration: 1500
        });
      } else {
        $scope.updateUserMsg();
      }
    };

    //修改签名 并保存用户信息
    $scope.editUsersignature = function() {
      $ionicLoading.show({
        template: "数据提交中",
        noBackdrop: true,
      });
      // 校验密码
      if (!checkText($scope.userMsg.signature)) {
        $ionicLoading.show({
          template: "请输入签名",
          noBackdrop: true,
          duration: 1500
        });
      } else {
        $scope.updateUserMsg();
      }
    };

    // 提交更新用户信息
    $scope.updateUserMsg = function() {
      // 更新用户信息
      // $$UserEditService.updateUser($scope.userMsg).success(function(data) {
      //   console.log(data);
      //   if (data.code == 200) { //修改成功
      //     // 改变当前用户信息
      //     $rootScope.userData.avatar = $scope.userMsg.avatar;
      //     $rootScope.userData.nickname = $scope.userMsg.nickname;
      //     // 同步用户缓存数据
      //     $$UserDataService.updateUserData($rootScope.userData);
      //     // 更新userMsg
      //     $scope.userMsg = {
      //       nickname: $rootScope.userData.nickname,
      //       password: "",
      //       avatar: $rootScope.userData.avatar
      //     };
      //     // 提示成功 关闭提示框
      //     $ionicLoading.show({
      //       template: data.message,
      //       noBackdrop: true,
      //       duration: 1500
      //     });
      //     $timeout(function() {
      //       $location.path("tab/user");
      //     }, 1500);
      //   } else if (data.code == 404) {
      //     $rootScope.needReLogin('useredit');
      //     return;
      //   } else {
      //     //数据提交失败，删除已上传图片
      //     $$UploadImageService.uploadDeleteImage($scope.userMsg.avatar).success(function(data) {});
      //     $ionicLoading.show({
      //       template: data.message,
      //       noBackdrop: true,
      //       duration: 1500
      //     });
      //   }
      // });
      if ($scope.userMsg.avatar == "") {
        $scope.userMsg.avatar = null;
      }

      $$UserEditService.updateUser($scope.userMsg)
        .then(function(res) {
          if (res.errCode === 203) {
            // 改变当前用户信息
            if ($rootScope.userData.headPic == $scope.userMsg.avatar) {} else {
              if ($scope.userMsg.avatar !== "" && $scope.userMsg.avatar !== null) {
                $rootScope.userData.headPic = $scope.userMsg.avatar;
              }
            }
            if ($rootScope.userData.signature == $scope.userMsg.signature) {} else {
              $rootScope.userData.signature = $scope.userMsg.signature;
            }
            // 同步用户缓存数据
            $$UserDataService.updateUserData($rootScope.userData);
            $ionicLoading.show({
              template: "修改成功",
              noBackdrop: true,
              duration: 1500
            });
            $timeout(function() {
              $location.path("tab/user");
            }, 1500);
          }
        });

    };

    // 退出登录
    // $scope.loginOut = function() {
    //     $ionicPopup.confirm({
    //         title: '退出登录',
    //         template: '确认退出登录？',
    //         cancelText: '取消',
    //         okText: "确定"
    //     }).then(function(res) {
    //         if (res) {
    //             $$LocalStorage.remove("userData");
    //             $rootScope.userData = $$UserDataService.getCacheUserData();
    //             // 如果是app端
    //             if ($rootScope.config.isWebView) {
    //                 // 设计极光推送别名为nologin
    //                 $$JPushService.setAlias("nologin");
    //             }
    //             $ionicLoading.show({
    //                 template: "退出登录...",
    //                 noBackdrop: true,
    //                 duration: 1000
    //             });
    //             $location.path("tab/user");
    //         } else {
    //             console.log('You are not sure');
    //         }
    //     });
    // };

  });
